// import PropTypes from 'prop-types'
import React, { memo, useEffect, useRef} from 'react'
import { IndicatorWrapper } from './style'

const Indicator = memo((props) => {
  const { curIndex = 0 } = props
  const contentRef = useRef()
  
  useEffect(() => {
    // 获取滚动区域
    const contentEl = contentRef.current
    const contentWidth = contentEl.clientWidth
    // 获取当前item的位置和宽度
    const itemOffsetLeft = contentEl.children[curIndex].offsetLeft
    const itemClientWidth = contentEl.children[curIndex].clientWidth
    // 获取滚动总长
    const contentScrollWidth = contentEl.scrollWidth
    // 计算当前要滚动的距离
    let distance = itemOffsetLeft + itemClientWidth * 0.5 - contentWidth * 0.5
    // 特殊情况
    if (distance < 0) distance = 0
    const totalDistance = contentScrollWidth - contentWidth
    if (distance > totalDistance) distance = totalDistance
    // 处理滚动
    contentEl.style.transform = `translate(${-distance}px)`
  }, [curIndex])

  return (
    <IndicatorWrapper>
      <div className="i-content" ref={contentRef}>
        {props.children}
      </div>
    </IndicatorWrapper>
  )
})

Indicator.propTypes = {}

export default Indicator